package com.cms.permission.aspect

import android.content.Context
import android.util.Log
import androidx.fragment.app.Fragment
import com.cms.permission.annotation.PermissionCancel
import com.cms.permission.annotation.PermissionDenied
import com.cms.permission.annotation.PermissionRequest
import com.cms.permission.inter.PermissionListener
import com.cms.permission.utils.PermissionUtils
import com.cms.permission.view.PermissionView
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Pointcut

/**
 * @author: Mr.You
 * @create: 2023-02-09 13:57
 * @description:
 **/
@Aspect
class PermissionAspectJ {

    @Pointcut("execution(@com.cms.permission.annotation.PermissionRequest  * *(..)) && @annotation(permissionRequest)")
     fun pointAspectJPermission(permissionRequest: PermissionRequest){

    }
    @Throws(Throwable::class)
    @Around("pointAspectJPermission(permissionRequest)")
    fun aProceedingJonPoint(joinPoint: ProceedingJoinPoint,permissionRequest: PermissionRequest){
       val  joinThis  = joinPoint.`this`
        var context:Context?=null
        if (joinThis is Context){
             context = joinThis as Context
        }else if (joinThis is Fragment){
            context = (joinThis as Fragment).context
        }
        if (context == null || permissionRequest ==null ){
            throw Exception("context or permissionRequest is not null")
        }
        PermissionView.requestPermission(context,permissionRequest.value,permissionRequest.requestCode,
            object :PermissionListener{
            override fun permissionGranted() {
                try {
                    joinPoint.proceed()
                }catch (e:java.lang.Exception){

                }
            }

            override fun permissionDenied() {
                PermissionUtils.invokeAnnotion(context,PermissionDenied::class.java)
            }

            override fun permissionCancel() {
                  PermissionUtils.invokeAnnotion(context,PermissionCancel::class.java)
            }

        })
    }
}